<template>
  <view class="login-container">
    <form @submit="handleLogin">
      <!-- 头像选择 -->
      <view class="avatar-section">
        <text class="section-title">选择头像</text>
        <button 
          class="avatar-btn"
          open-type="chooseAvatar" 
          @chooseavatar="handleChooseAvatar"
        >
          <image 
            :src="avatarUrl || defaultAvatarUrl" 
            class="avatar-image"
            mode="aspectFill"
          />
          <view class="avatar-mask">
            <text class="change-text">点击更换</text>
          </view>
        </button>
        <text class="avatar-tip">点击上方头像进行选择</text>
      </view>

      <!-- 昵称输入 -->
      <view class="nickname-section">
        <text class="section-title">填写昵称</text>
        <input
          class="nickname-input"
          type="nickname"
          v-model="nickname"
          placeholder="请输入昵称"
          @blur="handleNicknameBlur"
        />
        <text class="nickname-tip">建议使用2-12个字符</text>
      </view>

      <!-- 登录按钮 -->
      <button 
        class="login-btn" 
        form-type="submit" 
        :disabled="!isFormValid"
        :loading="isLoading"
      >
        {{ isLoading ? '登录中...' : '授权登录' }}
      </button>
    </form>

    <!-- 提示信息 -->
    <view class="tips" v-if="showTips && !isFormValid">
      <text>请设置头像和昵称完成登录</text>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      avatarUrl: '',    // 用户选择的头像
      nickname: '',     // 用户输入的昵称
      showTips: false,  // 显示提示信息
      isLoading: false, // 加载状态
      // 默认头像地址 - 使用您提供的URL
      defaultAvatarUrl: 'https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132'
    }
  },
  computed: {
    // 计算表单是否有效
    isFormValid() {
      return this.avatarUrl && this.nickname && this.nickname.trim().length >= 2;
    }
  },
  methods: {
    // 处理头像选择
    handleChooseAvatar(e) {
      console.log('头像选择事件:', e);
      const { avatarUrl } = e.detail;
      
      if (avatarUrl) {
        this.avatarUrl = avatarUrl;
        console.log('头像选择成功:', avatarUrl);
        
        // 可以在这里添加头像预览或立即上传的逻辑
        this.previewAvatar(avatarUrl);
      } else {
        // 安全检测未通过
        uni.showToast({
          title: '头像未通过安全检测',
          icon: 'none',
          duration: 2000
        });
      }
    },

    // 预览头像（可选）
    previewAvatar(avatarUrl) {
      // 如果需要预览大图可以取消注释下面的代码
      /*
      uni.previewImage({
        urls: [avatarUrl],
        current: avatarUrl
      });
      */
    },

    // 处理昵称输入
    handleNicknameBlur(e) {
      this.nickname = e.detail.value;
      console.log('昵称输入:', this.nickname);
      
      // 简单验证昵称长度
      if (this.nickname && this.nickname.trim().length < 2) {
        uni.showToast({
          title: '昵称至少2个字符',
          icon: 'none',
          duration: 1500
        });
      }
    },

    // 处理登录提交
    async handleLogin(e) {
      // 阻止默认表单行为
      e && e.preventDefault();
      
      // 验证表单
      if (!this.isFormValid) {
        this.showTips = true;
        setTimeout(() => {
          this.showTips = false;
        }, 2000);
        return;
      }

      this.isLoading = true;

      try {
        // 1. 获取登录code
        const loginCode = await this.getLoginCode();
        
        // 2. 构建用户信息对象
        const userInfo = {
          avatarUrl: this.avatarUrl,
          nickName: this.nickname.trim(),
          // 其他字段可以根据需要添加默认值
          gender: 0,
          country: '',
          province: '',
          city: '',
          language: 'zh_CN'
        };

        console.log('登录用户信息:', userInfo);
        console.log('登录code:', loginCode);
        
        // 3. 上传头像到服务器（如果需要永久存储）
        let finalAvatarUrl = this.avatarUrl;
        if (this.avatarUrl !== this.defaultAvatarUrl) {
          // 只有用户自定义的头像才需要上传
          finalAvatarUrl = await this.uploadAvatar(this.avatarUrl);
        }
        
        // 4. 完成登录流程
        await this.completeLogin(loginCode, {
          ...userInfo,
          avatarUrl: finalAvatarUrl
        });
        
        uni.showToast({
          title: '登录成功',
          icon: 'success',
          duration: 1500
        });
        
        // 登录成功后跳转页面
        setTimeout(() => {
          wx.reLaunch({
						url:'/pages/personal/personal'
					})
        }, 1500);

      } catch (error) {
        console.error('登录失败:', error);
        uni.showToast({
          title: '登录失败，请重试',
          icon: 'none',
          duration: 2000
        });
      } finally {
        this.isLoading = false;
      }
    },

    // 获取登录code
    getLoginCode() {
      return new Promise((resolve, reject) => {
        wx.login({
          success: (res) => {
            if (res.code) {
              resolve(res.code);
            } else {
              reject(new Error('获取登录code失败'));
            }
          },
          fail: reject
        });
      });
    },

    // 上传头像到服务器
    async uploadAvatar(tempFilePath) {
      try {
        // 显示上传进度
        uni.showLoading({
          title: '上传头像中...',
          mask: true
        });
        
        // 这里应该是您的实际上传逻辑
        console.log('开始上传头像:', tempFilePath);
        
        // 模拟上传过程（实际项目中替换为真实的API调用）
        await new Promise(resolve => setTimeout(resolve, 1500));
        
        // 返回服务器存储的URL（这里用临时路径模拟）
        // 实际项目中应该是服务器返回的永久URL
        return tempFilePath;
        
      } catch (error) {
        console.error('头像上传失败:', error);
        throw new Error('头像上传失败');
      } finally {
        uni.hideLoading();
      }
    },
    // 完成登录流程
    async completeLogin(code, userInfo) {
      // 这里实现您的登录逻辑，例如：
      // 1. 发送用户信息到后端
      // 2. 保存登录状态等
      
      console.log('完成登录:', { code, userInfo });
      
      // 模拟网络请求
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      // 保存用户信息到本地存储
      wx.setStorage({
				key:"userinfo",
				data:JSON.stringify(userInfo)
			})
    }
  },
  
  onLoad() {
    // 页面加载时设置默认头像
    this.avatarUrl = this.defaultAvatarUrl;
    console.log('使用默认头像:', this.defaultAvatarUrl);
  }
}
</script>

<style>
.login-container {
  padding: 60rpx 40rpx;
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  display: flex;
  flex-direction: column;
}

.avatar-section {
  margin-bottom: 50rpx;
  text-align: center;
  background: white;
  padding: 40rpx 30rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.section-title {
  display: block;
  font-size: 34rpx;
  font-weight: bold;
  margin-bottom: 30rpx;
  color: #333;
  text-align: center;
}

.avatar-btn {
  position: relative;
  width: 200rpx;
  height: 200rpx;
  padding: 0;
  margin: 0 auto 20rpx;
  border-radius: 50%;
  overflow: hidden;
  background: none;
  border: none;
  display: block;
}

.avatar-btn::after {
  border: none;
}

.avatar-image {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  border: 3rpx solid #f0f0f0;
}

.avatar-mask {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
  padding: 10rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}

.change-text {
  color: white;
  font-size: 24rpx;
  font-weight: 500;
}

.avatar-tip {
  display: block;
  font-size: 26rpx;
  color: #666;
  text-align: center;
  margin-top: 15rpx;
}

.nickname-section {
  margin-bottom: 50rpx;
  background: white;
  padding: 40rpx 30rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.nickname-input {
  background: #f9f9f9;
  padding: 25rpx 30rpx;
  border-radius: 12rpx;
  font-size: 30rpx;
  border: 2rpx solid #eee;
  margin-bottom: 15rpx;
}

.nickname-input:focus {
  border-color: #07C160;
}

.nickname-tip {
  font-size: 24rpx;
  color: #999;
  display: block;
}

.login-btn {
  background: linear-gradient(135deg, #07C160 0%, #05a150 100%);
  color: white;
  border-radius: 12rpx;
  font-size: 34rpx;
  font-weight: bold;
  height: 90rpx;
  line-height: 90rpx;
  box-shadow: 0 6rpx 20rpx rgba(7, 193, 96, 0.3);
  margin-top: 30rpx;
}

.login-btn:disabled {
  background: #CCCCCC;
  box-shadow: none;
}

.tips {
  margin-top: 30rpx;
  padding: 20rpx;
  background: #FFF6E6;
  border-radius: 12rpx;
  text-align: center;
  border: 1rpx solid #FFE4B8;
}

.tips text {
  color: #FF9A00;
  font-size: 26rpx;
}
</style>